package jjn.carl.monotonic_stack;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Scanner;

/**
 * @author Jiang Jining
 * @since 2023-08-27 9:21
 */
public class LeetCode503 {
    public int[] nextGreaterElements(int[] nums) {
        if (nums.length <= 1) {
            return new int[]{-1};
        }
        Deque<Integer> deque = new ArrayDeque<>();
        int[] next = new int[nums.length];
        Arrays.fill(next, -1);
        for (int i = 0; i < nums.length * 2; i++) {
            while (!deque.isEmpty() && nums[i % nums.length] > nums[deque.peekLast()]) {
                next[deque.peekLast()] = nums[i % nums.length];
                deque.pollLast();
            }
            deque.offer(i % nums.length);
        }
        return next;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = scanner.nextInt();
        int[] nums = new int[total];
        for (int i = 0; i < total; i++) {
            nums[i] = scanner.nextInt();
        }
        int[] nextGreaterElements = new LeetCode503().nextGreaterElements(nums);
        System.out.println(Arrays.toString(nextGreaterElements));
    }
}
